<template>
  <div class="page-title">营业汇总查询</div>
  <el-form class="search-form" inline :model="searchForm">
    <div>
      <el-form-item class="search-form-item" label="营业日期:">
        <el-date-picker
          v-model="searchForm.operDate"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间" 
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
          @change="handleDateChange"
           
        /> 
      </el-form-item>
      <el-form-item class="search-form-item" label="操作人:">
        <el-input
          v-model="searchForm.operUser"
          placeholder="请输入操作人"
        />
      </el-form-item>
      <el-form-item class="action-btn-box">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button class="reset-btn" @click="handleReset">清空筛选</el-button>
        <el-button class="reset-btn" @click="router.back()">返回</el-button>
      </el-form-item>
    </div>
  </el-form>
  <div class="table-box">
    <el-table :data="tableData" stripe v-loading="loading">
      <el-table-column prop="businessDate" label="营业日期" min-width="10%" >
        <template #default="scope">
          {{ subString(scope.row.businessDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="营业开始时间" min-width="10%" />
      <el-table-column prop="endDate" label="营业结束时间" min-width="8%" />
      <el-table-column prop="operName" label="日结操作人" min-width="8%"></el-table-column>
      <el-table-column prop="operDate" label="日结时间" min-width="8%" >
        <template #default="scope">
          <span>{{ scope.row.operDate? dayjs(scope.row.operDate).format('YYYY-MM-DD HH:mm'):'--'  }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作" min-width="16%" fixed="right">
        <template #default="scope">
          <!-- <el-button v-has-role="'cashier-businessSummary-dailySettle'" class="action-btn" style="width: 80px;" @click="handleDetail(scope.row,'1')">{{scope.row.statename === '日结' ? '反日结' : '日结'  }}</el-button> -->
             <!-- 日结/反日结按钮 -->
  <el-popconfirm
    v-has-role="'cashier-businessSummary-dailySettle'"
    class="action-btn"
    title="确认操作？"
    @confirm="handleDetail(scope.row,'1')"
    @cancel="handleCancelDailySettle"
  >
    <template #reference>
      <el-button
        style="border: 1px solid #FF6A00;color: #FF6A00;"
        class="action-btn-clor"
        >{{ scope.row.statename === '日结' ? '反日结' : '日结' }}</el-button>
    </template>
  </el-popconfirm>
          <el-button v-has-role="'cashier-businessSummary-reprint'" class="action-btn" @click="handleDetail(scope.row,'2')">补打营业汇总</el-button>
          <el-button v-has-role="'cashier-businessSummary-detail'" class="action-btn" @click="handleDetail(scope.row,'3')">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
    <div class="orderRecords-container-footer">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next,sizes, jumper"
            :total="total">
        </el-pagination>
        <button class="footer-button">确定</button>
    </div>

  <AllTableSelect
    v-model="allTableSelectShow"
    @cancel="allTableSelectShow = false"
    @confirm="selectTable"
  />
</template>
  
<script setup>
import AllTableSelect from "@/views/components/AllTableSelect.vue";
import { getLocalIPv4 } from "@/utils/getip.js";
import dayjs from "dayjs"
import Api from "@/api";

import { transformWorkTime } from '@/utils/chenhao.js' 
import useConfigStore from '@/store/config'  
const configStore = useConfigStore()
const orgStartTime = configStore.shopInfo.orgReportStartTime // orgStartTime
const orgEndTime = configStore.shopInfo.orgReportEndTime // orgEndTime  

const router = useRouter();

const handleDateChange = (newValue) => {
  console.log(newValue);
  const startDate = newValue[0].split(' ')[0]; // 提取第一个元素的日期部分
  const endDate = newValue[1].split(' ')[0];   // 提取第二个元素的日期部分
  const fullStartDateTime = `${startDate} ${orgStartTime}`;
  const fullEndDateTime = `${endDate} ${orgEndTime}`;
  searchForm.value.operDate = [fullStartDateTime,fullEndDateTime]
  console.log(fullStartDateTime);
  console.log(fullEndDateTime);
};
// 点击选择桌台
const allTableSelectShow = ref(false);
// 选中桌台
const selectTable = (data) => {
  if (data.name) {
    console.log(data);
    searchForm.value.roomCode = data.code;
    searchForm.value.roomName = data.name;
    allTableSelectShow.value = false;
  } else {
    ElNotification({
      title: "提示",
      message: "请选择桌号",
      type: "warning",
    });
  }
};
const subString = (timeString) => {
  let result = ''
  if(timeString){
    result = timeString.substring(0,10)
  }
  return result
}

const updateStatus = ref('')

const handleDetail = (item,type) => {
  if (type == 1) {
    if(item.statename == '未日结') {
          updateStatus.value = 1
        } else  {
          updateStatus.value = 0
      } 
    UpdateTableData(item.code,updateStatus.value)
  } else if (type == 2) { 
    BusinessSettlePrint(item)
  } else {
      router.push({
        path: '/Summary',
        query:{startTime:item.startDate,endTime:item.endDate}
      })
  }
}

let loading = ref(false);
let searchForm = ref({});
// 搜索
const handleSearch = (params) => {
  currentPage.value = 1;
  getTableData();
};
// 重置
const handleReset = (params) => {
  searchForm.value = {};
  handleSearch();
};
// 查询表格数据
let tableData = ref([{}]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
const handleSizeChange = (val) => {
  currentPage.value = 1
  pageSize.value = val;
  getTableData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getTableData();
};


//获取表格数据
const getTableData = (user) => {
  let query = {
    ...searchForm.value,
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  };
  if (query.operDate && query.operDate.length > 1) {
    query.startTime = query.operDate[0];
    query.endTime = query.operDate[1];
  }
  console.log("查询前的query :>> ", query);
  loading.value = true;
  // return
  Api.Common.PcObjProcess.Do({
    functionName: "GetBusinessSetList",
    contentData: query,
  }).then((res) => {
    console.log("查询订单table res--------- :>> ", res);
    loading.value = false;
    tableData.value = res.data;
    total.value = res.totalCount;

    tableData.value = res.data.map(obj => {
  
        if(obj.businessDate) {
          obj.businessDate = dayjs(obj.businessDate).format('YYYY-MM-DD HH:mm')
        }
        if (obj.startDate) {
          obj.startDate = dayjs(obj.startDate).format('YYYY-MM-DD HH:mm')
        }
        if (obj.endDate) {
          obj.endDate = dayjs(obj.endDate).format('YYYY-MM-DD HH:mm')
        }
        return obj
      })


  });
};

//更新日结状态
const UpdateTableData = (code,status) => {
  Api.Common.PcObjProcess.Do({
    functionName: "UpdateBusinessSet",
    contentData: {code:code,state:updateStatus.value},
  }).then((res) => {
    console.log(res,'xxxxxx')
    getTableData();
  });
};


//获取ip地址
const ip = ref("");
    getLocalIPv4()
    .then((ipAddress) => {
        // 在这里处理获取到的 IP 地址
        ip.value = ipAddress;
        console.log("IP 地址:", ip.value);
    })
    .catch((error) => {
        console.error("发生错误:", error);
        // 在这里处理错误情况
    });
    const BusinessSettlePrint = (item) => {
      let startDate = dayjs(item.startDate).format('YYYY-MM-DD HH:mm')
      let endDate = dayjs(item.endDate).format('YYYY-MM-DD HH:mm')
        Api.Common.PcObjProcess.Do({functionName:"BusinessSettlePrint",
          contentData:{"ip":ip.value,"handoverStartDate":startDate,"handoverEndDate":endDate}})
        .then(res=>{
            console.log(res)
            ElNotification({title: '提示',message: "打印成功", type: 'success'});
        })
    }


getTableData();
onMounted(()=> {
  searchForm.value.operDate = transformWorkTime('今天', orgStartTime, orgEndTime) // 默认今天
})

</script>
  
<style scoped lang="scss">
@import '@/styles/com_style_input.css';
/* 在这里编写组件的CSS样式 */
// .app-container {}
.search-form {
  width: 1520px;
  background: #ffffff;
  border-radius: 8px;
  padding: 20px 10px 0 40px;
  margin-bottom: 20px;

  // display: flex;
  .search-form-item {
    ::v-deep {
      .el-form-item__label {
        line-height: 40px;
      }

      .el-date-editor {
        width: 350px;
      }

      .el-input {
        width: 220px;
      }

      .el-input__wrapper {
        height: 40px;
        background: #fafafa;
        border-radius: 8px;
      }

      .el-select__wrapper {
        width: 220px;
        height: 40px;
        background: #fafafa;
        border-radius: 8px;
      }
    }
  }

  .range-item {
    .el-input {
      width: 130px;
    }
  }

  .action-btn-box {
    float: right;

    button {
      width: 120px;
      height: 48px;
      line-height: 48px;
      background: #ffe566;
      border-radius: 8px;
      border: 0;
      font-size: 16px;
      color: #212121;
    }

    .reset-btn {
      background: #e6e6e6;
      color: #666666;
    }
  }
}

.table-box {
  padding: 20px 40px;
  background: #ffffff;
  border-radius: 8px;
  width: 1520px;

  .total-box {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 20px;
    color: #212121;
  }
  .el-table--fit {
    height: 400px;
  }

  ::v-deep {
    .el-table__inner-wrapper::before {
      height: 0px;
    }

    .el-table th {
      font-size: 13px;
      font-weight: 700;
    }

    .el-table .el-table__header th,
    .el-table .el-table__header tr,
    .el-table .el-table__header td {
      height: 48px;
      background: #f9f9f9;
    }
  }

  
}

.pagination-box {
  margin-top: 20px;

  ::v-deep {
    .number {
      background: #e6e6e6 !important;
      border-radius: 8px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      font-size: 18px;
      color: #666666;
    }

    .number:hover {
      color: #ff6a00;
    }

    .is-active {
      background-color: #ff6a00 !important;
      border-radius: 8px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      font-size: 18px;
      color: #ffffff;
    }
  }
}

.color-FF6A00 {
  color: #ff6a00;
}

.page-title {
  font-family: Microsoft YaHei;
  font-weight: bold;
  font-size: 24px;
  color: #212121;
  margin-bottom: 10px;
}
.action-btn {
  padding: 0 10px;
    // width: 66px;
    height: 28px;
    border-radius: 4px;
    border: 1px solid #FF6A00;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #FF6A00;
  }
  ::v-deep .el-table .cell {
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 0.07292rem;
    color: #666666;
    line-height: 0.07292rem;
}

// ::v-deep .cashier-businessSummary-dailySettle {

// }
</style>
  